<script setup>
import { ref } from 'vue'
import { ElForm, ElFormItem, ElInput, ElButton } from 'element-plus'
import { userPwd } from '@/api/user'
import { useUserStore } from '@/stores'
import router from '@/router'
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})
const formRef = ref()
// 定义表单验证规则
const pwdFormRules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度为6-15位', trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度为6-15位', trigger: 'blur' },
    { validator: validateNotSame, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度为6-15位', trigger: 'blur' },
    { validator: validateConfirm, trigger: 'blur' }
  ]
}

// 自定义校验方法
function validateNotSame(rule, value, callback) {
  if (value === pwdForm.value.old_pwd) {
    callback(new Error('新密码不能与原密码相同'))
  } else {
    callback()
  }
}

function validateConfirm(rule, value, callback) {
  if (value !== pwdForm.value.new_pwd) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}
const UserStore = useUserStore()
// 提交表单
const submitForm = async () => {
  // 在这里处理表单提交逻辑
  await userPwd(pwdForm.value)
  ElMessage.success('修改密码成功')
  // 退出登录
  UserStore.removeToken()
  UserStore.setInfo({})
  router.push('/login')
}

// 重置表单
const resetForm = () => {
  // 清空表单数据
  pwdForm.value = { old_pwd: '', new_pwd: '', re_pwd: '' }
}
</script>
<template>
  <page-container title="修改密码">
    <el-form
      :model="pwdForm"
      :rules="pwdFormRules"
      ref="formRef"
      label-width="100px"
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="pwdForm.old_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="pwdForm.new_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="re_pwd">
        <el-input v-model="pwdForm.re_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">修改密码</el-button>
        <el-button style="margin-left: 10px" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>
